package com.term.util.oss;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import org.omg.CORBA.portable.ApplicationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

/**
 * 断点续传上传用法示例
 * Created by chengTaoYuan on 2017/1/19.
 */
public class OSSUploadUtil {
    private static final Logger logger = LoggerFactory.getLogger( OSSUploadUtil.class );

    private static String endpoint = "oss-cn-shanghai.aliyuncs.com";
    private static String accessKeyId = "LTAI4o01Je1vVIw2";
    private static String accessKeySecret = "kzGQSUpCDXGo6hJoiIVUEpxtSBUd9b";
    private static String bucketName = "aaaaaaaaaaaaaaaa";
    private static String key = "";
    private static String uploadFile = "";

    public static String uploadImg(HttpServletRequest request) {
        MultipartHttpServletRequest multiReq = ( MultipartHttpServletRequest ) request;
        MultipartFile file=multiReq.getFile("file");
        ObjectMetadata objectMetadata = new ObjectMetadata();
        if (file.isEmpty()) {
            return "";
        }
        if (file.getSize() > 1024 * 1024 * 2) {
            return "上传图片大小不能超过2M！";
        }
        Date nowTime=new Date();
        SimpleDateFormat time=new SimpleDateFormat("yyyy/MM");
        String imgDate=time.format(nowTime);
        // 获取文件名
        String fileName = file.getOriginalFilename();
        fileName="userHead/"+imgDate+"/"+fileName;
        key=fileName;
        logger.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        logger.info("上传的后缀名为：" + suffixName);
        String ossPath = System.currentTimeMillis() + file.getOriginalFilename();
        ossPath = ossPath.replaceAll( "\\\\", "/" );
        uploadFile=ossPath;

        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream instream = file.getInputStream();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            PutObjectResult putResult = ossClient.putObject(bucketName,  fileName, instream, objectMetadata);
            String ret = putResult.getETag();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ossPath="http://term-jhin.oss-cn-shanghai.aliyuncs.com/"+fileName;
        return ossPath;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase("jpeg") ||
                FilenameExtension.equalsIgnoreCase("jpg") ||
                FilenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase("pptx") ||
                FilenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase("docx") ||
                FilenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }
}
